import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, combineReducers} from 'redux';
const todoReducer = (state = [], action = {}) => {
  const { type, payload } = action;
  switch (type) {
    case "ADD_TODO_ITEM":
    return [...state, payload];
    default: return state;
  }
};

class TodoApp extends React.Component {
  saveTODO() {
    this.props.savaFun({
      type: "ADD_TODO_ITEM",
      payload: this.refs.ipt.value
    });
  }
  render() {
    var todos = this.props.data.map(function(item, idx){
      return <li key={idx}>{item}</li>;
    });
    return (
      <div>
        <input type="text" ref="ipt" />
        <input type="button" value="添加todo" onClick={this.saveTODO.bind(this)} />
        <ul>{todos}</ul>
      </div>
    )
  }
}

const store = createStore(todoReducer);

function render() {
  ReactDOM.render(
    <TodoApp data={store.getState()} savaFun={store.dispatch} />,
    document.querySelector('#example')
  );
}
render();
store.subscribe(render);
